<style lang="less">
    @import './index.less';
</style>

<template>
    <div class="user-list-view">
        <Card>
            <p slot="title">用户列表</p>
            <span slot="extra">
                <Button icon="plus" type="success" size="small" @click.prevent="batchGiveScore">批量赠送积分</Button>
                <Button icon="loop" type="success" size="small" @click.prevent="getData">刷新列表</Button>
            </span>
            <Form label-position="right" label-width="70" inline>
                <Row>
                    <FormItem label-width="0">
                        <Input style="width: 180px;" size="small" placeholder="账号/手机号" v-model="search.keyword"></Input>
                    </FormItem>
                    <FormItem label="注册时间:">
                        <DatePicker size="small" @on-change="handleChangeDate" type="datetimerange" placeholder="请选择时间段" style="width:260px"></DatePicker>
                    </FormItem>
                    <FormItem label="省市区：">
                        <Cascader style="margin-top:5px; width: 250px;" :data="regions" change-on-select size="small" trigger="click" v-model="regionSelected"></Cascader>
                    </FormItem>
                    <FormItem label-width="0">
                        <Button type="success" :loading="searchLoading" size="small" icon="ios-search"
                                @click="handleSearch">筛选
                        </Button>
                    </FormItem>
                </Row>
            </Form>
            <Row>
                <Col>
                    <Table border="true" :loading="loading" stripe="true" height="450" :context="self" :columns="columns" :data="data"></Table>
                </Col>
            </Row>
            <Row style="padding: 5px 0">
                <Col>
                    <Page ref="Page"
                          :total="page.total"
                          :size="page.size"
                          @on-change="handleChangePage"
                          @on-page-size-change="handleChangePageSize"
                          :page-size-opts="page.sizes" show-sizer show-elevator></Page>
                </Col>
            </Row>
        </Card>

        <Modal ref="editModel" v-model="editModel">
            <p slot="header" style="color:#f60;text-align:center">
                <span>修改用户信息</span>
            </p>
            <div style="text-align:center">
                <editForm :row.sync="editRow" :row-index.sync="editRowIndex" :root-node="this" @on-change="handleEdited"></editForm>
            </div>
            <div slot="footer"></div>
        </Modal>
    </div>
</template>

<script>
    import util from '@/libs/util';
    import expandRow from './ExpandRow.vue';
    import editForm from './EditForm.vue';

    const editButton = (vm, h, row, index) => {
        return h('a', {
            style: {
                margin: '5px'

            },
            on: {
                'click': (event) => {
                    vm.edit(row, index)
                }
            }
        }, '修改');
    };

    const chargeButton = (vm, h, row, index) => {
        return h('a', {
            style: {
                margin: '5px'

            },
            on: {
                'click': (event) => {
                    vm.charge(row, index)
                }
            }
        }, '充值');
    };

    const giveScoreButton = (vm, h, row, index) => {
        return h('a', {
            style: {
                margin: '5px'

            },
            on: {
                'click': (event) => {
                    vm.giveScore(row, index)
                }
            }
        }, '赠送积分');
    };

    const toggleStatusButton = (vm, h, row, index) => {
        return h('Poptip', {
            props: {
                confirm: true,
                title: '您确定要修改该用户的账号状态吗?',
                transfer: true
            },
            on: {
                'on-ok': () => {
                    vm.updateStatus(row, index);
                }
            }
        }, [
            h('a', {
                style: {
                    margin: '5px',
                    color: row.is_effect ? 'red' : 'green'
                }
            }, row.is_effect ? '禁用' : '启用')
        ]);
    };

    export default {
        components: {
            expandRow,
            editForm
        },

        data () {
            return {
                self: this,
                loading: false,
                editModel: false,
                editRow: {},
                editRowIndex: '',
                page: {
                    total: 0,
                    current: 1,
                    size: 10,
                    sizes: [10, 30, 50, 100],
                },
                columns: [
//                    {
//                        type: 'expand',
//                        width: 50,
//                        render: (h, params) => {
//                            return h(expandRow, {
//                                props: {
//                                    row: params.row
//                                }
//                            })
//                        }
//                    },
                    {
                        title: '用户ID',
                        key: 'id',
                        width: 80
                    },
                    {
                        title: '账号',
                        key: 'name',
                        width: 120,
                    },
                    {
                        title: '地区',
                        key: 'full_address',
                        width: 220,
                    },
                    {
                        title: '性别',
                        key: 'sex_text',
                        width: 80,
                    },
                    {
                        title: '账户余额(元)',
                        key: 'balance',
                        width: 120,
                    },
                    {
                        title: '积分余额(个)',
                        key: 'score',
                        width: 120,
                    },
                    {
                        title: '来源',
                        key: 'source_text',
                        width: 120,
                    },
                    {
                        title: '状态',
                        key: 'is_effect',
                        width: 80,
                    },
                    {
                        title: '注册时间',
                        key: 'created_at',
                        width: 180,
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 150,
                        align: 'center',
                        fixed: 'right'
                    }
                ],
                data: [],

                searchLoading: false,
                search: {
                    keyword: '',
                    province_code: '',
                    city_code: '',
                    district_code: '',
                    created_at: []
                },

                regions: [],
                regionSelected: [],
                regionLoading: false,

                batchGiveSearch: {
                    province_code: '',
                    city_code: '',
                    district_code: '',
                },
                batchGiveScoreNum: 0,
            }
        },

        created () {
            this.init();
        },

        mounted () {
            this.getData();
            this.getRegions();
        },

        watch: {
            'page': (page) => {
                this.$refs.Page.total = page.total;
                this.$refs.Page.current = page.current;
            },

            regionSelected: function (newVal) {
                if (newVal) {
                    if (newVal.length > 2) {
                        this.search.district_code = newVal[2];
                    } else {
                        this.search.district_code = '';
                    }

                    if (newVal.length > 1) {
                        this.search.city_code = newVal[1];
                    } else {
                        this.search.city_code = '';
                    }

                    if (newVal.length > 0) {
                        this.search.province_code = newVal[0];
                    } else {
                        this.search.province_code = '';
                    }
                } else {
                    this.search.province_code = '';
                    this.search.city_code = '';
                    this.search.district_code = '';
                }
            }
        },

        methods: {
            handleChangeDate (date) {
                if (date[1] != undefined) {
                    this.search.created_at = date;
                } else {
                    this.search.created_at = [];
                }
            },

            init () {
                let vm = this;

                this.columns.forEach(item => {
                    if (item.key == 'action') {
                        item.render = (h, param) => {
                            let buttons = [];

                            buttons.push(toggleStatusButton(vm, h, param.row, param.index));

                            let userRoles = this.$store.state.user.user.roles_name || [];
                            if (util.anyInOf(userRoles, ['admin', 'system'])) {
                                buttons.push(chargeButton(vm, h, param.row, param.index));
                                buttons.push(h('div'));
                                buttons.push(giveScoreButton(vm, h, param.row, param.index));
                            }
                            return buttons;
                        };
                    }

                    if (item.key == 'is_effect') {
                        item.render = (h, param) => {
                          if (param.row.is_effect == 1) {
                              return h('span', {
                                  style: {
                                      color: 'green'
                                  }
                              }, '已启用');
                          } else {
                              return h('span', {
                                  style: {
                                      color: 'red'
                                  }
                              }, '已禁用');
                          }
                        };
                    }
                });
            },

            getData () {
                this.$Message.loading('数据加载中...');
                this.loading = true;
                let params = {
                    page: this.page.current,
                };
                params = Object.assign(params, this.search);
                util.api().get(`/admin/api/users`, {
                    headers: {
                        pageSize: this.page.size,
                    },
                    params
                }).then((resp) => {
                    this.$Message.destroy();
                    if (resp.data.status == true) {
                        this.data = resp.data.data;
                        this.page.total = resp.data.meta.total;
                        this.page.current = resp.data.meta.current_page;
                    } else {
                        this.$Message.error(resp.data.message);
                    }
                    this.loading = false;
                    this.searchLoading = false;
                }).catch((e) => {
                    this.$Message.destroy();
                    if (e.response) {
                        this.$Notice.error({ title: '网络请求异常', desc: e.response.data.message});
                    } else {
                        this.$Message.error('网络请求错误');
                    }
                    this.loading = false;
                    this.searchLoading = false;
                });
            },

            handleSearch() {
                this.searchLoading = true;
                this.page.current = 1;
                this.getData();
            },

            handleChangePage (page) {
                this.page.current = page;
                this.getData();
            },

            handleChangePageSize (size) {
                this.page.size = size;
                this.getData();
            },

            handleEdited(row, index) {
                this.data[index] = row;
            },

            edit (row, index) {
                this.editModel = true;
                this.editRow = row;
                this.editRowIndex = index;
            },

            updateStatus (row, index) {
                let newStatus = row.is_effect == 1 ? 0 : 1;

                util.api().patch(`/admin/api/users/${row.id}/status/${newStatus}`).then((resp) => {
                   if (resp.data.status == true) {
                       this.data[index].is_effect = newStatus;
                       this.$Message.success(resp.data.message);
                   } else {
                       this.$Message.error(resp.data.message);
                   }
                }).catch((e) => {
                    if (e.response) {
                        if (e.response.status == 422) {
                            if (e.response.data.hasOwnProperty('errors')) {
                                for (let i in e.response.data.errors) {
                                    this.$Notice.error({ title: '表单数据验证失败', desc: e.response.data.errors[i][0] });
                                }
                            }
                        } else {
                            this.$Message.error(e.response.data.message);
                        }
                    }  else {
                        this.$Message.error('网络请求异常');
                    }
                });
            },

            charge (row, index) {
                let money = 0;
                let that = this;
                this.$Modal.confirm({
                    render: (h) => {
                        return h('InputNumber', {
                            style: {
                              margin: '40px 0 -20px 0',
                              width: '100%'
                            },
                            props: {
                                value: 1,
                                autofocus: true,
                                min: 1,
                                max: 200,
                                placeholder: '请输入充值金额'
                            },
                            on: {
                                input: (val) => {
                                    money = val;
                                }
                            }
                        })
                    },
                    title: '账户余额充值',
                    width: 200,
                    onOk: () => {
                        if (money < 1 || money > 200) {
                            that.$Message.error('充值金额必须大于或者等于1元，最多充值200元');
                        } else {
                            util.api().post(`/admin/api/users/${row.id}/backend/charge/${money}`).then((resp) => {
                                if (resp.data.status == true) {
                                    that.data[index].balance += money;
                                    that.$Message.success(resp.data.message);
                                } else {
                                    that.$Message.error(resp.data.message);
                                }
                            }).catch((e) => {
                                util.handleApiException(e, that, '账户余额充值失败');
                            });
                        }
                    }
                })
            },

            giveScore (row, index) {
                let score = 1;
                let that = this;
                this.$Modal.confirm({
                    render: (h) => {
                        return h('InputNumber', {
                            style: {
                              margin: '40px 0 -20px 0',
                              width: '100%'
                            },
                            props: {
                                value: score,
                                autofocus: true,
                                min: 1,
                                max: 200,
                            },
                            on: {
                                input: (val) => {
                                    score = val;
                                }
                            }
                        })
                    },
                    title: '赠送积分',
                    width: 200,
                    onOk: () => {
                        if (score < 1 || score > 2000) {
                            that.$Message.error('赠送积分数量必须大于或者等于1个，最多赠送2000个');
                        } else if (!Number.isInteger(score)) {
                            that.$Message.error('赠送积分数量必须是整数');
                        } else {
                            util.api().post(`/admin/api/users/give/score`, {user_id: row.id, score: score}).then((resp) => {
                                if (resp.data.status == true) {
                                    that.data[index].score += score;
                                    that.$Message.success(resp.data.message);
                                } else {
                                    that.$Message.error(resp.data.message);
                                }
                            }).catch((e) => {
                                util.handleApiException(e, that, '积分赠送失败');
                            });
                        }
                    }
                })
            },

            batchGiveScore () {
                let score = 1;
                let that = this;
                this.$Modal.confirm({
                    render: (h) => {
                        let elements = [];

                        elements.push(h('Cascader', {
                            class: 'ivu-cascader-trigger-hover',
                            style: {
                                margin: '40px 0 0',
                                width: '100%'
                            },
                            props: {
                                data: that.regions,
                                'change-on-select': '',
                                trigger: 'click',
                                placeholder: '请选择赠送的用户区域范围'
                            },
                            on: {
                                'on-change': (data, selectedData) => {
                                    if (data) {
                                        if (data.length > 2) {
                                            that.batchGiveSearch.district_code = data[2];
                                        } else {
                                            that.batchGiveSearch.district_code = '';
                                        }

                                        if (data.length > 1) {
                                            that.batchGiveSearch.city_code = data[1];
                                        } else {
                                            that.batchGiveSearch.city_code = '';
                                        }

                                        if (data.length > 0) {
                                            that.batchGiveSearch.province_code = data[0];
                                        } else {
                                            that.batchGiveSearch.province_code = '';
                                        }
                                    } else {
                                        that.batchGiveSearch.province_code = '';
                                        that.batchGiveSearch.city_code = '';
                                        that.batchGiveSearch.district_code = '';
                                    }
                                }
                            }
                        }));

                        elements.push(h('InputNumber', {
                            style: {
                                margin: '40px 0 -20px 0',
                                width: '100%'
                            },
                            props: {
                                value: score,
                                autofocus: true,
                                min: 1,
                                max: 2000,
                                placeholder: '请输入充值金额'
                            },
                            on: {
                                input: (val) => {
                                    score = val;
                                }
                            }
                        }));

                        return elements;
                    },
                    title: '批量赠送积分',
                    width: 220,
                    onOk: () => {
                        if (score < 1 || score > 2000) {
                            that.$Message.error('赠送积分数量必须大于或者等于1个，最多赠送2000个');
                        } else if (!Number.isInteger(score)) {
                            that.$Message.error('赠送积分数量必须是整数');
                        } else {
                            let params = {score: score};
                            params = Object.assign(params, that.batchGiveSearch);
                            util.api().post(`/admin/api/users/batch/give/score`, params).then((resp) => {
                                if (resp.data.status == true) {
                                    that.getData();
                                    that.$Notice.info({
                                        title: '批量赠送积分通知'
                                        ,desc: resp.data.message
                                        ,duration: 10
                                    });
                                } else {
                                    that.$Message.error(resp.data.message);
                                }
                            }).catch((e) => {
                                util.handleApiException(e, that, '批量积分赠送失败');
                            });
                        }
                    }
                })
            },

            getRegions () {
                this.regionLoading = true;
                util.ajax.get('/api/regions/format').then((resp) => {
                    const formatTree = (arr) => {
                        let regions = [];
                        for (let i in arr) {
                            let node = {};
                            node.value = arr[i].code;
                            node.label = arr[i].name;
                            node.disabled = arr[i].disabled;
                            if (arr[i].hasOwnProperty('children')) {
                                node.children = formatTree(arr[i].children);
                            }

                            regions.push(node);
                        }
                        return regions;
                    };

                    this.regions = formatTree(resp.data.data);
                    this.regionLoading = false;
                }).catch((e) => {
                    this.regionLoading = false;
                    util.handleApiException(e, this, '获取省市区数据失败');
                })
            }
        }
    };
</script>

<style>

</style>
